const Koa = require('koa')
const path = require('path')
const fs = require('fs')
const compilerSfc = require('@vue/compiler-sfc')
const compilerDom = require('@vue/compiler-dom')
const app = new Koa()
app.use(context => {
    const { request: { url, query } } = context
    console.log('request', url, query)
    console.log(url)
    const routePath = url.split('?')[0]
    if (routePath == '/') {
        const content = fs.readFileSync(path.resolve(__dirname, 'index.html'), 'utf-8')
        context.type = 'text/html'
        context.body = content
    }
    else if (routePath.endsWith('.js')) {
        const content = fs.readFileSync(path.resolve(__dirname, routePath.slice(1)), 'utf-8')
        context.type = 'application/javascript'
        context.body = replaceImportModule(content)
    }
    else if (routePath.startsWith('/@module')) {
        const moduleName = routePath.replace('/@module/', '')
        const modulePath = path.resolve(__dirname, 'node_modules', moduleName)
        console.log(modulePath)
        const pkg = require(path.join(modulePath, 'package.json'))
        const moduleEsmPath = path.join(modulePath, pkg.module)
        const content = fs.readFileSync(moduleEsmPath, 'utf-8')
        context.type = 'application/javascript'
        context.body = replaceImportModule(content)
    }
    else if (routePath.endsWith('.css')) {
        const content = fs.readFileSync(path.resolve(__dirname, routePath.slice(1)), 'utf-8')
        context.type = 'application/javascript'
        context.body = `
            const style = document.createElement('style')
            style.setAttribute('type','text/css')
            style.innerHTML = \`${content}\`
            document.body.append(style)
        `
    }
    else if (routePath.indexOf('.vue') > -1) {
        if (!query.type) {
            const sfcFileContent = fs.readFileSync(path.resolve(__dirname, routePath.slice(1)), 'utf-8')
            const { descriptor } = compilerSfc.parse(sfcFileContent)
            console.log(descriptor)
            let content = descriptor.script.content.replace('export default defineComponent', `
        import { render } from '${routePath}?type=template'\r\n
        import '${routePath}?type=css'\r\n
        const script = defineComponent`)
            content += `
        script.render = render\r\n
        export default script\r\n`
            context.type = 'application/javascript'
            context.body = replaceImportModule(content)
        } else if (query.type == 'template') {
            const sfcFileContent = fs.readFileSync(path.resolve(__dirname, routePath.slice(1)), 'utf-8')
            const { descriptor } = compilerSfc.parse(sfcFileContent)
            const template = compilerDom.compile(descriptor.template.content, { mode: "module" })
            context.type = 'application/javascript'
            context.body = replaceImportModule(template.code)
            // context.body = replaceImportModule(template.code.replace('const _Vue = Vue', `import _Vue from 'vue'`).replace('return function render', 'export function render'))
        } else if (query.type == 'css') {
            const sfcFileContent = fs.readFileSync(path.resolve(__dirname, routePath.slice(1)), 'utf-8')
            const { descriptor } = compilerSfc.parse(sfcFileContent)
            const content = descriptor.styles.reduce((code, it) => {
                return code + it.content
            }, '')
            context.type = 'application/javascript'
            context.body = `
                const style = document.createElement('style')
                style.innerHTML = \`${content}\`
                document.body.append(style)
            `
        }
    }

})
function replaceImportModule(code) {
    return code.replace(/([import|export]) (.*) from ['|"]([^'"\.]+)['|"]/g, function (a, b, c, d) {
        return `${b} ${c} from '/@module/${d}'`
    })
}
app.listen(3000, () => {
    console.log('koa start at 3000')
})
